package com.stx.test.day0911;

/**
 * packageName com.stx.day0909
 *
 * @author YangYi
 * @className binarySearch
 * @date 2025/9/10
 * @description TODO
 */
public class BinarySearch {
    public static void main(String[] args) {
        // 定义一个数组
        int[] arrays = {1,3,5,6,7,8,9,11,15};
        // 定义一个查找的数字
        int num = 15;
        // 二分查找法
        int result = binarySearchMethod(arrays,num);
        System.out.println("查找结果（-1为不存在数字内）："+result);
    }

    /**
     * 二分查找法
     * @param arrays
     * @param num
     * @return
     */
    public static int binarySearchMethod(int[] arrays,int num){
        int minLength = 0;
        int maxLength = arrays.length - 1;
        while(minLength <= maxLength){
            int mid = (maxLength + minLength) / 2;
            if(num == arrays[mid]){
                return mid;
            }else if(num < arrays[mid]){
                maxLength = mid - 1;
            }else {
                minLength = mid +1;
            }
        }
        return -1;
    }
}
